#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <cstring>
#include <string>

using namespace std;

const int NUM = 5;
int tickets = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

class threadData
{
public:
    threadData(int num)
    {
        threadname = "thread-" + to_string(num);
    }

public:
    string threadname;
};

void* getTickets(void* args)
{
    threadData* td = static_cast<threadData*>(args);
    const char* name = td->threadname.c_str();

    while(true)
    {
        pthread_mutex_lock(&lock);
        if(tickets > 0)
        {
            usleep(1000);
            tickets--;
            printf(" %s get a ticket: %d\n", name, tickets);
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }
        usleep(15);
    }
    printf("%s...quit\n", name);

    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    vector<threadData*> thread_datas;

    for(int i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData(i);
        thread_datas.push_back(td);
        pthread_create(&tid, nullptr, getTickets, thread_datas[i-1]);
        tids.push_back(tid);
    }

    for(auto t : tids)
    {
        pthread_join(t, nullptr);
    }

    for(auto td : thread_datas)
    {
        delete td;
    }

    return 0;
}